import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getInfo } from "@/api/login";

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/logout', '/auth-redirect', '/bind']

router.beforeEach((to, from, next) => {
  NProgress.start();
  // console.log(to)

  // 如果已经登录，直接跳转
  const hasLogin = store.getters.user.hasLogin;
  if (hasLogin) {
    gotoPath(to, from, next);
    return;
  }
  // 验证是否已登录
  getInfo(true, to.query).then(resp => {
    store.dispatch("StoreUserInfo", resp)
    .then((accessedRoutes) => {
      // console.log(accessedRoutes);
      gotoPath(to, from, next, accessedRoutes);
    })
    .catch((err) => {
      console.log(err)
      gotoPath(to, from, next);
    });
  }).catch(err => {
    console.log(err);
    gotoPath(to, from, next);
  });

})

function gotoPath(to, from, next, accessedRoutes) {
  const hasLogin = store.getters.user.hasLogin;
  if (!hasLogin) {
    // 未登录
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
    return;
  }
  if (accessedRoutes) {
    router.addRoutes(accessedRoutes); // 动态添加可访问路由表
  }
  /* 已登录直接跳转首页*/
  if (to.path === '/login') {
    next({ path: '/' });
    NProgress.done();
  } else {
    if (accessedRoutes) {
      next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
    } else {
      next();
    }
  }
}

router.afterEach(() => {
  NProgress.done()
})
